package com.wh.wisdomsite.xbox.server.controller.vi;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.wh.wisdomsite.xbox.common.util.ResManager;
import com.wh.wisdomsite.xbox.pojo.vi.VideoProjectIn;
import com.wh.wisdomsite.xbox.server.manager.UserMapManager;
import com.wh.wisdomsite.xbox.server.util.UserUtils;
import com.wh.wisdomsite.xbox.utils.StringUtils;
import com.wh.wisdomsite.xbox.utils.date.DateTool;
import com.wh.wisdomsite.xbox.utils.json.JsonUtil;
import com.wh.wisdomsite.xbox.utils.json.JsonUtil_Org;
import com.wh.wisdomsite.xbox.vi.entity.VideoProject;
import com.wh.wisdomsite.xbox.vi.service.IVideoProjectService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/***
 *视频设备项目配置控制层
 * @author 杨世强
 * @date 16:49 2018/8/2
 * @Copyright 公司版权所有
 * @Company 贵州万华科技有限公司Copyright (c) 2016
 * @version V1.0
 */
@Controller
@RequestMapping(value = "/videoProject")
public class VideoProjectController {

    private static final Log logger = LogFactory.getLog(VideoProjectController.class);

    @Autowired
    private IVideoProjectService iVideoProjectService;

    /**
     * 跳转到视频设备项目配置
     *
     * @return
     */
    @RequiresPermissions("rules:vi_videoProject_page")
    @RequestMapping(value = "/index.do", method = RequestMethod.GET)
    public String index() {
        return "vi/videoProject/videoProjectList";
    }

    /**
     * 获取视频设备项目配置列表
     *
     * @param response
     * @param in
     */
    @RequiresPermissions("rules:vi_videoProject_find")
    @RequestMapping(value = "/videoProjectList.do")
    public void videoProjectList(HttpServletResponse response, VideoProjectIn in) {
        try {
            logger.info("加载视频设备项目配置列表-->>开始");
            if (in.getPage() == 0) in.setPage(1);
            if (in.getRows() == 0) in.setRows(10);
            Page<VideoProject> page = new Page<VideoProject>();
            page.setCurrent(in.getPage());
            page.setSize(in.getRows());
            //设置条件
            EntityWrapper<VideoProject> ewVideoProject = new EntityWrapper<VideoProject>();
            ewVideoProject.setEntity(new VideoProject());
            if (StringUtils.isNotEmpty(in.getPrId())) {
                ewVideoProject.eq("v.prId", in.getPrId());
            }
            if (StringUtils.isNotEmpty(in.getVpName())) {
                ewVideoProject.like("v.vpName", in.getVpName());
            }
            if (StringUtils.isNotEmpty(in.getDeviceId())) {
                ewVideoProject.eq("v.deviceId", in.getDeviceId());
            }
            if (null != in.getOnLineStatus()) {
                ewVideoProject.eq("v.onLineStatus", in.getOnLineStatus());
            }
            //若不是超级管理员则根据用户权限添加查询条件
            if(!UserUtils.isSysAdmin()){
                ewVideoProject = UserUtils.setEntityWrapper(ewVideoProject, "co", "off", "pr");
            }
            ewVideoProject.orderBy("v.createDate", false);
            Page<Map<String, Object>> videoProjectPage = iVideoProjectService.getMapsPage(page, ewVideoProject);
            JSONObject json = new JSONObject();
            JSONArray array = new JSONArray();
            if (videoProjectPage.getRecords().size() > 0) {
                for (Map<String, Object> videoProject : videoProjectPage.getRecords()) {
                    JSONObject object = new JSONObject(videoProject);
                    object.put("createDate", DateTool.getFormatDateByMs(videoProject.get("createDate")));
                    if (videoProject.get("project") != null) {
                        object.put("project", new JSONObject(videoProject.get("project")));
                    }
                    if (videoProject.get("hkUser") != null) {
                        object.put("hkUser", new JSONObject(videoProject.get("hkUser")));
                    }
                    array.put(object);
                }
            }
            json.put("total", videoProjectPage.getTotal());
            json.put("rows", array);
            ResManager.getJsonOut(response).print(json);
            logger.info("加载视频设备项目配置列表-->>结束");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 视频设备项目配置详情
     *
     * @param id
     * @param request
     * @return
     */
    @RequestMapping(value = "/videoProjectDesc.do")
    public String videoProjectDesc(String id, String source, HttpServletRequest request) {
        logger.info("视频设备项目配置详情-->>开始");
        Map<String, Object> videoProject = iVideoProjectService.getMapById(id);
        if(videoProject.get("createBy")!=null){
            videoProject.put("createBy",UserMapManager.getUserLoginNameInMap(videoProject.get("createBy").toString()));
        }
        if(videoProject.get("updateBy")!=null){
            videoProject.put("updateBy",UserMapManager.getUserLoginNameInMap(videoProject.get("updateBy").toString()));
        }
        request.setAttribute("videoProject", videoProject);
        request.setAttribute("source", source);
        logger.info("视频设备项目配置详情-->>结束");
        return "vi/videoProject/videoProjectDesc";
    }


    /**
     * 删除视频设备项目配置
     * @param id
     * @param response
     */
    @RequiresPermissions("rules:vi_videoProject_del")
    @RequestMapping(value = "delVideoProject.do", method = RequestMethod.GET)
    public void delVideoProject(String id, HttpServletResponse response) {
        try {
            logger.info("删除视频设备项目配置-->>开始");
            iVideoProjectService.deleteById(id);
            logger.info("删除视频设备项目配置-->>结束");
            ResManager.getJsonOut(response).print(JsonUtil_Org.returnTrue("删除成功"));
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("删除视频设备项目配置-->>Exception" + e.getMessage());
        }
    }


    /**
     * 跳转至添加页面
     *
     * @return
     */
    @RequestMapping("/toVideoProject.do")
    public ModelAndView toVideoProject(String id, String source, HttpServletRequest request) {
        logger.info("添加视频设备项目配置跳转-->>开始");
        VideoProject videoProject = new VideoProject();
        if (StringUtils.isNotEmpty(id)) {
            videoProject = iVideoProjectService.selectById(id);
        }
        request.setAttribute("videoProject", videoProject);
        request.setAttribute("source", source);
        logger.info("添加视频设备项目配置跳转-->>结束");
        return new ModelAndView("vi/videoProject/videoProjectOption");
    }


    /**
     * 更新或修改视频设备项目配置
     *
     * @param videoProject
     * @param response
     */
    @RequiresPermissions("rules:vi_videoProject_edit")
    @RequestMapping(value = "/save.do", method = RequestMethod.POST)
    public void save(VideoProject videoProject,HttpServletResponse response) {
        //查看视频设备是否已经存在
        try {
            if (StringUtils.isNotEmpty(videoProject.getVpId())) {
                logger.info("修改视频设备项目配置-->>开始");
                //设置更新人
                videoProject.setUpdateBy(UserUtils.getCurrentUser().getUsId());
                videoProject.setUpdateDate(new Date());
                iVideoProjectService.updateById(videoProject);
                logger.info("修改视频设备项目配置-->>结束");
                response.getWriter().write(JsonUtil_Org.returnTrue("更新视频设备项目配置成功"));
            } else {
                logger.info("添加视频设备项目配置-->>开始");
                //设置创建人
                videoProject.setCreateBy(UserUtils.getCurrentUser().getUsId());
                videoProject.setCreateDate(new Date());
                iVideoProjectService.insert(videoProject);
                logger.info("添加视频设备项目配置-->>结束");
                response.getWriter().write(JsonUtil_Org.returnTrue("添加视频设备项目配置成功"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("添加视频设备项目配置-->>Exception" + e.getMessage());
        }
    }

    /**
     * 获取设备编号
     *
     * @param response
     */
    @RequestMapping(value = "/getDeviceIdList.do")
    public void getDeviceIdList(HttpServletResponse response, String prId) {
        List<VideoProject> videoProjectList = new ArrayList<VideoProject>();
        try {
            logger.info("获取设备编号-->>开始");
            EntityWrapper<VideoProject> ewVideoProject = new EntityWrapper<VideoProject>();
            ewVideoProject.setEntity(new VideoProject());
            if (StringUtils.isNotEmpty(prId)) {
                ewVideoProject.eq("prId", prId);
            }
            ewVideoProject.groupBy("deviceId");
            videoProjectList = iVideoProjectService.selectList(ewVideoProject);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("获取设备编号-->>异常Exception " + e.getMessage());
        }
        ResManager.getJsonOut(response).print(JsonUtil.Json2All(videoProjectList));
        logger.info("获取设备编号-->>结束");
    }



    /**
     * 获取视频设备总数
     * @param response
     */
    @RequestMapping("/getTotal.do")
    public void getTotal(HttpServletResponse response) {
        try {
            logger.info("获取视频设备总数-->>开始");
            //设置条件
            EntityWrapper<VideoProject> ewVideoProject = new EntityWrapper<VideoProject>();
            ewVideoProject.setEntity(new VideoProject());
            ewVideoProject.eq("v.dataState", "1");
            //若不是超级管理员则根据用户权限添加查询条件
            if(!UserUtils.isSysAdmin()){
                ewVideoProject = UserUtils.setEntityWrapper(ewVideoProject, "co", "off", "pr");
            }
            Map<String, Object> total = iVideoProjectService.getTotal(ewVideoProject);
            Object totalNumber = total.get("totalNumber");
            JSONObject json = new JSONObject();
            json.put("totalNumber",totalNumber);
            ResManager.getJsonOut(response).print(json);
            logger.info("获取视频设备总数-->>结束");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
